import React, { useState, useEffect, useRef } from 'react';
import { Input, Tag } from 'antd';
import styled from 'styled-components';

const SelectLikeWrapper = styled.div`
  position: relative;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  min-height: 32px;
  padding: 0 7px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
  cursor: text;
  transition: all 0.3s;

  &:hover {
    border-color: #40a9ff;
  }

  &:focus-within {
    border-color: #40a9ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  .ant-input {
    border: none !important;
    box-shadow: none !important;
    flex: 1;
    min-width: 60px;
    height: 30px;
    padding: 0 4px;

    &::placeholder {
      color: #bfbfbf;
      font-size: 14px;
    }

    &:disabled {
      background: transparent;
      cursor: not-allowed;
    }
  }

  .ant-tag {
    margin: 2px 4px 2px 0;
  }
    .ant-tag {
  transition: all 0.3s;
  animation: tagIn 0.3s ease-in;
}

@keyframes tagIn {
  from { opacity: 0; transform: translateY(4px); }
  to { opacity: 1; transform: translateY(0); }
}
`;

const MultipleInput = ({
  value = [],
  onChange,
  maxTags = 5,
  placeholder = '请输入...',
  disabled,
  ...rest
}) => {
  const [inputValue, setInputValue] = useState('');
  const inputRef = useRef(null);

  // 自动聚焦输入框
  useEffect(() => {
    if (!disabled && value?.length < maxTags) {
      inputRef.current?.focus();
    }
  }, [value, disabled, maxTags]);

  const handleConfirm = () => {
    const val = inputValue.trim();
    if (val && value?.length < maxTags) {
      const newValues = [...(value || []), val];
      onChange?.(newValues);
      setInputValue('');
    }
  };

  const handleRemove = (index) => {
    const newValues = value.filter((_, i) => i !== index);
    onChange?.(newValues);
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Backspace' && !inputValue) {
      handleRemove(value.length - 1);
    }
    if ((e.key === ',' || e.key === ' ') && value?.length < maxTags) {
      e.preventDefault();
      handleConfirm();
    }
  };

  return (
    <SelectLikeWrapper onClick={() => !disabled && inputRef.current?.focus()}>
      {value?.map((tag, index) => (
        <Tag
          key={index}
          closable={!disabled}
          onClose={() => handleRemove(index)}
        >
          {tag}
        </Tag>
      ))}

      {!disabled && value?.length < maxTags && (
        <Input
          {...rest}
          ref={inputRef}
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onPressEnter={handleConfirm}
          onKeyDown={handleKeyDown}
          placeholder={value?.length === 0 ? placeholder : ''}
          bordered={false}
          disabled={disabled || value?.length >= maxTags}
        />
      )}
    </SelectLikeWrapper>
  );
};

export default MultipleInput;